package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Slf4j
@Transactional
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private VMService vmService;
	@Autowired
	private TaskDetailsService taskDetailsService;

	@Autowired
	private MqttProducer mqttProducer;

	@Override
	public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
		Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
		LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
		if (!Strings.isNullOrEmpty(innerCode)) {
			qw.eq(TaskEntity::getInnerCode, innerCode);
		}
		if (userId != null && userId > 0) {
			qw.eq(TaskEntity::getUserId, userId);
		}
		if (!Strings.isNullOrEmpty(taskCode)) {
			qw.like(TaskEntity::getTaskCode, taskCode);
		}
		if (status != null && status > 0) {
			qw.eq(TaskEntity::getTaskStatus, status);
		}
		if (isRepair != null) {
			if (isRepair) {
				qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
			} else {
				qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
			}
		}
		if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
			qw
					.ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
					.le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
		}
		//根据最后更新时间倒序排序
		qw.orderByDesc(TaskEntity::getUpdateTime);

		return Pager.build(this.page(page, qw));
	}

	/**
	 * 新增工单
	 *
	 * @param vo
	 * @return
	 */
	@Override
	public boolean create(TaskViewModel vo) {

		//检查创建工单状态
		checkCreateTask(vo);

		//判断同一台设备下是否存在未完成的工单
		if (hasTask(vo)) {
			throw new LogicException("该机器有未完成的同类型工单");
		}

		//新增工单表记录
		TaskEntity taskEntity = new TaskEntity();
		//复制属性到实体
		BeanUtils.copyProperties(vo, taskEntity);
		//生成工单编号,抽取了方法
		String taskCode = generateTaskCode();
		//设置实体属性
		taskEntity.setTaskCode(taskCode);
		taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
		taskEntity.setProductTypeId(vo.getProductType());
		//fegin调用vm-service
		VmVO vmInfo = vmService.getVMInfo(vo.getInnerCode());
		//继续给实体类属性赋值
		taskEntity.setAddr(vmInfo.getNodeAddr());
		taskEntity.setRegionId(vmInfo.getRegionId());

		//保存
		this.save(taskEntity);

		//如果是补货,还需要跟新明细表
		if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
			vo.getDetails().forEach(d -> {
				TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
				BeanUtils.copyProperties(d, taskDetailsEntity);
				taskDetailsEntity.setTaskId(taskEntity.getTaskId());
				taskDetailsService.save(taskDetailsEntity);
			});
		}

		return true;
	}

	@Override
	public boolean accept(Long id) {
		TaskEntity taskEntity = this.getById(id);
		if(taskEntity.getTaskStatus()!= VMSystem.TASK_STATUS_CREATE ){
			throw new LogicException("工单状态不是待处理");
		}
		taskEntity.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
		return this.updateById(taskEntity);
	}

	@Override
	public boolean cancelTask(Long id, CancelTaskViewModel cancelVm) {
		TaskEntity task = this.getById(id);  //查询工单
		if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
			throw new LogicException("工单已经结束");
		}
		task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
		task.setDesc(cancelVm.getDesc());
		updateTaskZSet(task, -1);
		return this.updateById(task);
	}

	@Override
	public boolean completeTask(Long id) {
		TaskEntity taskEntity = this.getById(id);
		if(taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_FINISH  || taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_CANCEL ){
			throw new LogicException("工单已经结束");
		}
		taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
		this.updateById(taskEntity);

		//如果是投放工单或撤机工单
		if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_DEPLOY
				|| taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_REVOKE){
			noticeVMServiceStatus(taskEntity);//运维工单封装与下发
		}

		//如果是补货工单!!!!---------------------------
		if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_SUPPLY){
			noticeVMServiceSupply(taskEntity);
		}


		return true;
	}

	/**
	 * 补货协议封装与下发
	 * @param taskEntity
	 */
	private void noticeVMServiceSupply(TaskEntity taskEntity) {
		//协议内容封装
		//1.根据工单id查询工单明细表
		QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
		qw.lambda()
				.eq(TaskDetailsEntity::getTaskId,taskEntity.getTaskId());
		List<TaskDetailsEntity> details = taskDetailsService.list(qw);
		//2.构建协议内容
		SupplyContract supplyContract = new SupplyContract();
		supplyContract.setInnerCode(taskEntity.getInnerCode());//售货机编号
		List<SupplyChannel> supplyChannels = Lists.newArrayList();//补货数据
		//从工单明细表提取数据加到补货数据中
		details.forEach(d->{
			SupplyChannel channel = new SupplyChannel();
			channel.setChannelId(d.getChannelCode());
			channel.setCapacity(d.getExpectCapacity());
			supplyChannels.add(channel);
		});
		supplyContract.setSupplyData(supplyChannels);
		//3.下发补货协议
		//发送到emq
		try {
			mqttProducer.send( TopicConfig.VMS_SUPPLY_TOPIC,2, supplyContract );
		} catch (Exception e) {
			log.error("发送工单完成协议出错");
			throw new LogicException("发送工单完成协议出错");
		}
	}

	/**
	 * 运维工单封装与下发
	 * @param taskEntity
	 */
	private void noticeVMServiceStatus(TaskEntity taskEntity) {
		//向消息队列发送消息，通知售货机更改状态
		//封装协议
		TaskCompleteContract taskCompleteContract=new TaskCompleteContract();
		taskCompleteContract.setInnerCode(taskEntity.getInnerCode());//售货机编号
		taskCompleteContract.setTaskType( taskEntity.getProductTypeId() );//工单类型
		//发送到emq
		try {
			mqttProducer.send( TopicConfig.VMS_COMPLETED_TOPIC,2, taskCompleteContract );
		} catch (Exception e) {
			log.error("发送工单完成协议出错");
			throw new LogicException("发送工单完成协议出错");
		}
	}

	private boolean hasTask(TaskViewModel vo) {
		LambdaQueryWrapper<TaskEntity> lqw = new LambdaQueryWrapper<>();
		lqw.select(TaskEntity::getTaskId)
				.eq(TaskEntity::getInnerCode, vo.getInnerCode())
				.eq(TaskEntity::getProductTypeId, vo.getProductType())
				.le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
		return count(lqw) > 0;
	}

	private void checkCreateTask(TaskViewModel vo) {
		String innerCode = vo.getInnerCode();
		int productType = vo.getProductType();

		VmVO vmInfo = vmService.getVMInfo(innerCode);//根据设备编号查询设备
		if (vmInfo == null) {
			throw new LogicException("设备校验失败");
		}
		//如果是投放工单，状态为运营
		if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
			throw new LogicException("该设备已在运营");
		}

		//如果是补货工单，状态不是运营状态
		if (productType == VMSystem.TASK_TYPE_SUPPLY && !vmInfo.getVmStatus().equals(VMSystem.VM_STATUS_RUNNING)) {
			throw new LogicException("该设备不在运营状态");
		}

		//如果是撤机工单，状态不是运营状态
		if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
			throw new LogicException("该设备不在运营状态");
		}
	}

	/**
	 * 封装的方法,生成工单编号
	 *
	 * @return
	 */
	private String generateTaskCode() {
		String datetime = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
		//自定义字字符串加日期,作为key存入redis
		String key = "lkd.task.code" + datetime;
		Object obj = redisTemplate.opsForValue().get(key);
		if (obj == null) {
			redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
			return datetime + "0001";
		}
		return datetime + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
	}


	/**
	 * 更新工单量列表
	 * @param taskEntity
	 * @param score
	 */
	private void  updateTaskZSet(TaskEntity taskEntity,int score){
		String roleCode="1003";//运维员
		if(taskEntity.getProductTypeId().intValue()==2){//如果是补货工单
			roleCode="1002";//运营员
		}
		String key= VMSystem.REGION_TASK_KEY_PREF
				+ LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
				+"."+ taskEntity.getRegionId()+"."+roleCode;
		redisTemplate.opsForZSet().incrementScore(key,taskEntity.getUserId(),score);
	}

}
